package com.ryl.yomall.wxservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.google.gson.Gson;
import com.ryl.yomall.model.cart.CartInfo;
import com.ryl.yomall.model.common.constant.RedisConst;
import com.ryl.yomall.model.common.exception.YomallException;
import com.ryl.yomall.model.common.result.Result;
import com.ryl.yomall.model.user.UserInfo;
import com.ryl.yomall.user.client.UserFeignClient;
import com.ryl.yomall.wxservice.entity.UcenterMember;
import com.ryl.yomall.wxservice.mapper.UcenterMemberMapper;
import com.ryl.yomall.wxservice.service.UcenterMemberService;
import com.ryl.yomall.wxservice.utils.ConstantPropertiesUtil;
import com.ryl.yomall.wxservice.utils.HttpClientUtils;

import com.ryl.yomall.wxservice.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import javax.security.sasl.SaslServer;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author ryl
 * @since 2020-12-02
 */

@Controller
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberMapper ucenterMemberMapper;
    @Autowired
    private UcenterMemberService memberService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserFeignClient userFeignClient;
    @PostMapping("add")
    public Result add(HttpSession session){
        UcenterMember ucenterMember =new UcenterMember ();
        ucenterMember.setOpenid("123");
        ucenterMember.setNickname("lisi");
        ucenterMember.setAvatar("headimgurl");
        ucenterMember.setIsDisabled(false);
        ucenterMemberMapper.insert (ucenterMember  );
        return Result.ok ();

    }

    @GetMapping("login")
    public String wxLogin(String originUrl,HttpSession session){
        System.out.println ( originUrl);
        session.setAttribute ( "aa","123" );
        session.setAttribute ( "originUrl",originUrl );
        redisTemplate.opsForValue ().set ( "originUrl",originUrl,15,TimeUnit.DAYS);

        //1拼写地址
        //方式一：https://open.weixin.qq.com/connect/qrconnect?
        // appid=APPID&redirect_uri=REDIRECT_URI
        // &response_type=code&scope=SCOPE&state=STATE
        //方式二：
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String qrcodeUrl = String.format(
                baseUrl,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                redirectUrl,
                "wxryl");

        return "redirect:" + qrcodeUrl;
    }


    @GetMapping("callback")
    public String  callback(String code, String state){
        System.out.println("code="+code);
        System.out.println("state="+state);
        String originUrl = (String) redisTemplate.opsForValue ( ).get ( "originUrl" );


        //1向认证服务器发送请求换取access_token
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        String accessTokenUrl = String.format(baseAccessTokenUrl,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code);

        String accessTokenResult="";
        try {
            accessTokenResult= HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessTokenResult="+accessTokenResult);
        } catch (Exception e) {
            throw new YomallException ("获取access_token失败",20001 );
        }
        //2json串解析获取access_token，openid
        Gson gson = new Gson();
        HashMap<String,String> accessTokenMap = gson.fromJson(accessTokenResult, HashMap.class);
        String access_token = accessTokenMap.get("access_token");
        String openid = accessTokenMap.get("openid");
        //3 用access_token，openid访问微信换取用户信息
        String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=%s" +
                "&openid=%s";
        String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
        String resultUserInfo = null;
        try {
            resultUserInfo = HttpClientUtils.get(userInfoUrl);
            System.out.println("resultUserInfo==========" + resultUserInfo);
        } catch (Exception e) {
            throw new YomallException ("获取用户信息失败",20001 );
        }

        HashMap<String,String> userInfoMap = gson.fromJson(resultUserInfo, HashMap.class);
        String nickname = userInfoMap.get("nickname");
        String headimgurl = userInfoMap.get("headimgurl");
        //4根据openid判断用户是否注册
        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<> ();
        wrapper.eq("openid",openid);
        UcenterMember ucenterMember = memberService.getOne(wrapper);
        //5如果没有注册，注册用户
        if(ucenterMember==null){
            userFeignClient.addWxUser ( nickname );
            ucenterMember = new UcenterMember();
            ucenterMember.setOpenid(openid);
            ucenterMember.setNickname(nickname);
            ucenterMember.setAvatar(headimgurl);
            ucenterMember.setIsDisabled(false);
            memberService.save(ucenterMember);
        }
        //6用户登录
        String token = JwtUtils.getJwtToken(ucenterMember.getId(),ucenterMember.getNickname());


//        try {
//            originUrl = URLDecoder.decode (  originUrl,"utf-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace ( );
//        }

        System.out.println ( originUrl);
        try {
            nickname= URLEncoder.encode(nickname,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace ( );
        }
        return "redirect:"+originUrl+"?nickname="+nickname;
    }


}


